package cn.hacynn.nd.controller;

import cn.hacynn.nd.common.constant.MessageConstant;
import cn.hacynn.nd.config.AliPayConfiguration;
import cn.hacynn.nd.mapper.OrderMapper;
import cn.hacynn.nd.pojo.entity.Orders;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.alipay.easysdk.factory.Factory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Hacynn
 * @Date 2024/6/5 8:38
 * @Version 1.0
 */

@RestController
@RequestMapping("/alipay")
@Transactional(rollbackFor = Exception.class)
public class AliPayController {

    @Autowired
    private AliPayConfiguration aliPayConfig;
    @Autowired
    private OrderMapper orderMapper;


    private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT ="JSON";
    private static final String CHARSET ="utf-8";
    private static final String SIGN_TYPE ="RSA2";


    /**
     * 支付宝支付接口
     * @param orderNo
     * @param httpResponse
     * @throws Exception
     */
    @GetMapping("/pay") // /alipay/pay?orderNo=xxx
    public void pay(String orderNo, HttpServletResponse httpResponse) throws Exception {
        // 查询订单信息
        Orders orders = orderMapper.selectOne(new QueryWrapper<Orders>().eq("order_no", orderNo));
        if (orders == null) {
            // 订单不存在
            throw new AlipayApiException(MessageConstant.ORDER_NOT_EXIST);
        }
        // 1.创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 2.创建Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 设置回调地址
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        // 设置订单信息
        JSONObject bizContent = new JSONObject();
        bizContent.set("out_trade_no", orders.getOrderNo());   // 自己生成的订单编号（必须唯一）
        bizContent.set("total_amount", orders.getTotal());  // 订单的总金额
        bizContent.set("subject", orders.getGoodsName());  // 支付的名称
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
        request.setBizContent(bizContent.toString());
        // request.setReturnUrl("http://localhost:8099/");   // 支付完成后跳转的页面

//        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
//                + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
//                + "\"subject\":\"" + aliPay.getGoodsName() + "\","
//                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();   // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /**
     * 支付宝接口回调函数
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");  // 订单编号
            String gmtPayment = params.get("gmt_payment");  // 支付时间
            String alipayTradeNo = params.get("trade_no");  // 支付宝交易编号
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                // 更新订单为已支付
                Date payTime = DateUtil.parse(gmtPayment, "yyyy-MM-dd HH:mm:ss");
                Orders orders = orderMapper.selectById(tradeNo);
                orders.setPayNo(alipayTradeNo);
                orders.setPayTime(payTime);
                orders.setStatus(1);
                orderMapper.updateById(orders);
            }
        }
        return "success";
    }
}